package com.cloudfun.campusshare.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.constant.RoleType;
import com.cloudfun.campusshare.common.model.dto.SchoolInfoImportDTO;
import com.cloudfun.campusshare.common.model.vo.DeviceSchoolExportVO;
import com.cloudfun.campusshare.common.model.vo.SchoolAddVO;
import com.cloudfun.campusshare.common.response.BaseResult;
import com.cloudfun.campusshare.common.response.BaseResultFactory;
import com.cloudfun.campusshare.common.security.AuthRequired;
import com.cloudfun.campusshare.entity.SchoolEntity;
import com.cloudfun.campusshare.repo.SchoolEntityRepository;
import com.cloudfun.campusshare.service.SchoolService;
import com.cloudfun.campusshare.util.BeanCopyUtil;
import com.cloudfun.campusshare.util.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @author : ashsr.zhang
 * @date : 2020/3/3 17:17
 * @Version : v1.0
 * @description 学校信息接口
 **/
@RestController
@RequestMapping("/v1/school")
@Api(value = "学校信息")
@Validated
@Slf4j
public class SchoolController {
    @Autowired
    private SchoolService schoolService;

    @Resource
    private SchoolEntityRepository schoolEntityRepository;

    @PostMapping("/add")
    @ApiOperation(value = "新增学校信息")
    @AuthRequired(role = RoleType.ADMIN)
    @ResponseBody
    public BaseResult addSchool(@ApiParam(value = "schoolAddVO", required = true)@RequestBody SchoolAddVO schoolAddVO){
        schoolService.addSchool(schoolAddVO);
        return BaseResultFactory.produceEmptyResult(Code.SUCCESS);
    }

    @GetMapping("/list")
    @ApiOperation(value = "查询学校信息列表")
    @AuthRequired(role = {RoleType.ADMIN,RoleType.OPERATIONAL_MERCHANT})
    @ResponseBody
    public BaseResult querySchoolList(Pageable pageable, @ApiParam(value = "关键字") @RequestParam(required = false)String keyword){
        return  BaseResultFactory.produceResult(Code.SUCCESS, schoolService.getSchoolList(pageable,keyword));
    }


    @PostMapping("/batch/add")
    @ApiOperation(value = "学校信息批量导入")
    @AuthRequired(role = RoleType.ADMIN)
    @ResponseBody
    public BaseResult batchImport(MultipartFile file) throws Exception {
        if(file.isEmpty()){
            return BaseResultFactory.produceEmptyResult(Code.ERROR);
        }
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        importParams.setImportFields(SchoolInfoImportDTO.FIELDS);

        List<SchoolInfoImportDTO> schoolList = ExcelImportUtil.importExcel(file.getInputStream(), SchoolInfoImportDTO.class, importParams);
        if(CollectionUtils.isEmpty(schoolList)){
            return BaseResultFactory.produceEmptyResult(Code.ERROR,"excel不能为空");
        }
        schoolList.parallelStream().forEach(x -> {
            SchoolEntity schoolEntity = BeanCopyUtil.copy(x, SchoolEntity.class);
            schoolEntityRepository.save(schoolEntity);
        });
        return BaseResultFactory.produceEmptyResult(Code.SUCCESS);
    }

    @PostMapping("/delete/{schoolId}")
    @ApiOperation(value = "删除学校信息")
    @AuthRequired(role = RoleType.ADMIN)
    @ResponseBody
    public BaseResult deleteSchool(@ApiParam(value = "学校id",required = true)@PathVariable String schoolId){
        schoolService.deleteSchool(schoolId);
        return BaseResultFactory.produceEmptyResult(Code.SUCCESS);
    }

    @GetMapping("/detail/{schoolId}")
    @ApiOperation(value = "获取学校详细信息")
    @AuthRequired(role = {RoleType.ADMIN,RoleType.FINANCIAL_INSTITUTIONS})
    @ResponseBody
    public BaseResult getDetailSchoolInfo(@ApiParam(value = "学校id",required = true)@PathVariable String schoolId){
        return BaseResultFactory.produceResult(Code.SUCCESS,schoolService.getSchoolDetail(schoolId));
    }

    @GetMapping("/device/list")
    @ApiOperation(value = "获取学校关联的设备列表信息")
    @AuthRequired(role = RoleType.ADMIN)
    @ResponseBody
    public BaseResult getSchoolDeviceList(Pageable pageable, @ApiParam(value = "学校id",required = true)@RequestParam String schoolId){
        return BaseResultFactory.produceResult(Code.SUCCESS,schoolService.getSchoolDeviceList(pageable,schoolId));
    }

    @GetMapping("/device/export")
    @ApiOperation(value = "导出学校关联的设备列表信息")
    @AuthRequired(role = RoleType.ADMIN)
    @ResponseBody
    public BaseResult exportSchoolList(@ApiParam(value = "学校id",required = true)@RequestParam String schoolId, HttpServletResponse response) throws IOException {
        List<DeviceSchoolExportVO> schoolExportList = schoolService.getSchoolExportList(schoolId);
        String schoolName = schoolEntityRepository.findById(schoolId).get().getName();
        ExcelUtils.exportExcel(schoolExportList, null, "设备列表", DeviceSchoolExportVO.class,
                schoolName + "-AssociatedDevices", response);
        return BaseResultFactory.produceEmptyResult(Code.SUCCESS);
    }
}
